import "./picker-sfc.css";
import {
  defineComponent,
  reactive,
  watch,
  nextTick,
  getCurrentInstance
} from "vue";
import { createNamespace } from "../utils";
import FanPopup from "../popup/popup.js";
import FanButton from "../button/button.js";
import FanText from "../text/text.js";
import PickerColumn from "./picker-column.js";
const __vue_sfc__ = defineComponent({
  name: createNamespace("Picker")[0],
  options: { virtualHost: true },
  emits: ["confirm", "cancel", "update:modelValue", "update:show"],
  components: { FanPopup, FanButton, FanText, PickerColumn },
  props: {
    modelValue: {
      type: Array,
      default: () => []
    },
    show: {
      type: Boolean,
      default: false
    },
    title: String,
    cancelText: {
      type: String,
      default: "\u53D6\u6D88"
    },
    confirmText: {
      type: String,
      default: "\u786E\u8BA4"
    },
    data: Array,
    valueKey: String,
    textKey: {
      type: String,
      default: "text"
    }
  },
  setup(props, { emit }) {
    const state = reactive({
      innerShow: props.show,
      list: [],
      selectValue: props.modelValue && props.modelValue.length ? [...props.modelValue] : []
    });
    let isCascade = false;
    const instance = getCurrentInstance();
    const selectItem = (val) => {
      if (state.selectValue[val.level] !== val.select) {
        state.selectValue[val.level] = val.select;
        if (isCascade) {
          const d = state.list[val.level][val.index];
          state.list.splice(val.level + 1, state.list.length);
          if ((d == null ? void 0 : d.children) && (d == null ? void 0 : d.children.length))
            formatCascade({
              data: d.children,
              key: props.textKey,
              arr: state.list
            });
          state.list.forEach((_item, i) => {
            var _a;
            if (i > val.level) {
              state.selectValue[i] = (_a = state.list[i]) == null ? void 0 : _a.findIndex(
                (item) => !item.disabled
              );
              nextTick(() => {
                const column = instance.refs.column.sort(
                  (a, b) => a.index - b.index
                );
                column[i].onTouchEnd(state.list[i]);
              });
            }
          });
        }
      }
    };
    const onConfirm = () => emit("confirm", state.selectValue);
    const onCancel = () => {
      state.innerShow = false;
      emit("cancel");
    };
    const formatCascade = ({ data, key, arr }) => {
      const l = data.map((item) => ({
        text: item[key],
        disabled: !!(item == null ? void 0 : item.disabled),
        [props.valueKey]: item[props.valueKey],
        children: item.children
      }));
      arr.push(l);
      if (l[0].children && l[0].children.length)
        formatCascade({ data: l[0].children, key, arr });
    };
    const init = ({ data, key, arr }) => {
      if (data && data.length) {
        if (typeof data[0] === "string") {
          if (!state.selectValue.length)
            state.selectValue = [0];
          arr.push(data.map((text) => ({ text, disabled: false })));
        } else if (Array.isArray(data[0])) {
          data.forEach((items, i) => {
            arr.push([]);
            items.forEach((item) => {
              arr[i].push({
                disabled: !!(item == null ? void 0 : item.disabled),
                text: item[key],
                [props.valueKey]: item[props.valueKey]
              });
            });
          });
          if (!state.selectValue.length) {
            state.selectValue = [];
            arr.forEach((items) => {
              const index = items.findIndex((item) => {
                if (!item.disabled)
                  return true;
              });
              state.selectValue.push(
                props.valueKey ? items[index][props.valueKey] : index
              );
            });
          }
        } else {
          isCascade = true;
          formatCascade({ data, key, arr });
          if (!state.selectValue.length) {
            state.selectValue = [];
            setTimeout(() => {
              state.list.forEach((items) => {
                const index = items.findIndex((item) => {
                  if (!item.disabled)
                    return true;
                });
                state.selectValue.push(
                  props.valueKey ? items[index][props.valueKey] : index
                );
              });
            }, 0);
          }
        }
      }
    };
    watch(
      () => props.modelValue,
      (val) => {
        if (val)
          state.selectValue = [...val];
      },
      { deep: true }
    );
    watch(
      () => state.selectValue,
      (val) => {
        let alike = false;
        if (val.find((item, i) => item !== props.modelValue[i]))
          alike = true;
        if (alike)
          emit("update:modelValue", val);
      },
      { deep: true }
    );
    watch(
      () => props.show,
      (val) => state.innerShow = val
    );
    watch(
      () => state.innerShow,
      (val) => emit("update:show", val)
    );
    watch(
      () => props.data,
      (data) => {
        if (data && data.length) {
          const arr = [];
          init({ data, key: props.textKey, arr });
          state.list = arr;
        }
      },
      { immediate: true, deep: true }
    );
    return { state, onConfirm, onCancel, selectItem };
  }
});
import { renderSlot as _renderSlot, toDisplayString as _toDisplayString, createTextVNode as _createTextVNode, resolveComponent as _resolveComponent, withCtx as _withCtx, createVNode as _createVNode, openBlock as _openBlock, createElementBlock as _createElementBlock, renderList as _renderList, Fragment as _Fragment, createBlock as _createBlock, createElementVNode as _createElementVNode } from "vue";
const _hoisted_1 = {
  key: 1,
  class: "fan-picker__o fan-flex fan-align-center fan-justify-between"
};
const _hoisted_2 = { class: "fan-picker__c" };
function __vue_render__(_ctx, _cache) {
  const _component_FanButton = _resolveComponent("FanButton");
  const _component_FanText = _resolveComponent("FanText");
  const _component_PickerColumn = _resolveComponent("PickerColumn");
  const _component_FanPopup = _resolveComponent("FanPopup");
  return _openBlock(), _createBlock(_component_FanPopup, {
    show: _ctx.state.innerShow,
    "onUpdate:show": _cache[0] || (_cache[0] = ($event) => _ctx.state.innerShow = $event),
    "safe-bottom": "",
    position: "bottom"
  }, {
    default: _withCtx(() => [
      _createElementVNode("div", null, [
        _ctx.$slots.header ? _renderSlot(_ctx.$slots, "header", { key: 0 }) : (_openBlock(), _createElementBlock("div", _hoisted_1, [
          _createVNode(_component_FanButton, {
            plain: "",
            border: false,
            "text-size": "14",
            "text-color": "#969799",
            onClick: _ctx.onCancel
          }, {
            default: _withCtx(() => [
              _createTextVNode(
                _toDisplayString(_ctx.cancelText),
                1
                /* TEXT */
              )
            ]),
            _: 1
            /* STABLE */
          }, 8, ["onClick"]),
          _createVNode(_component_FanText, {
            bold: "",
            "text-size": "18",
            color: "#333"
          }, {
            default: _withCtx(() => [
              _createTextVNode(
                _toDisplayString(_ctx.title),
                1
                /* TEXT */
              )
            ]),
            _: 1
            /* STABLE */
          }),
          _createVNode(_component_FanButton, {
            plain: "",
            border: false,
            "text-size": "14",
            "text-color": "var(--fan-primary-color)",
            onClick: _ctx.onConfirm
          }, {
            default: _withCtx(() => [
              _createTextVNode(
                _toDisplayString(_ctx.confirmText),
                1
                /* TEXT */
              )
            ]),
            _: 1
            /* STABLE */
          }, 8, ["onClick"])
        ])),
        _createElementVNode("div", _hoisted_2, [
          (_openBlock(true), _createElementBlock(
            _Fragment,
            null,
            _renderList(_ctx.state.list, (item, i) => {
              return _openBlock(), _createBlock(_component_PickerColumn, {
                ref_for: true,
                ref: "column",
                key: i,
                items: item,
                value: _ctx.state.selectValue,
                index: i,
                "value-key": _ctx.valueKey,
                onSelectItem: _ctx.selectItem
              }, null, 8, ["items", "value", "index", "value-key", "onSelectItem"]);
            }),
            128
            /* KEYED_FRAGMENT */
          )),
          _cache[1] || (_cache[1] = _createElementVNode(
            "div",
            {
              class: "fan-picker__b",
              style: { height: "44PX", top: "132PX" }
            },
            null,
            -1
            /* HOISTED */
          )),
          _cache[2] || (_cache[2] = _createElementVNode(
            "div",
            { class: "fan-picker__mask" },
            null,
            -1
            /* HOISTED */
          ))
        ])
      ])
    ]),
    _: 3
    /* FORWARDED */
  }, 8, ["show"]);
}
__vue_sfc__.render = __vue_render__;
var stdin_default = __vue_sfc__;
export {
  stdin_default as default
};
